import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user'
import type {
  loginForm,
  loginResponseData,
  userInfoResponseData,
} from '@/api/user/type'
import type { UserState } from './types/type'
import { set_token, get_token } from '@/utils/token'
// 引入常量路由
import { constantRoutes, asyncRoutes, anyRoutes } from '@/router/routes'
import router from '@/router';
// @ts-ignore
import cloneDeep from 'lodash/cloneDeep.js'

// 用于过滤当前用户需要的异步路由
function filterAsyncRoutes(asyncRoutes: any, routes: any) {
  return asyncRoutes.filter((item:any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoutes(item.children, routes)
      }
      return true
    }
  })
}


let useUserStore = defineStore('User', {
  state: (): UserState => {
    return {
      token: get_token() || '',
      menuRoutes: constantRoutes,
      name: '',
      avatar: '',
      buttons: [],
    }
  },
  actions: {
    // 用户登录
    async userLogin(data: loginForm) {
      let res: loginResponseData = await reqLogin(data)
      console.log(res, 'res')
      if (res.code === 200) {
        this.token = res.data
        set_token(this.token)
        return 'ok'
      } else {
        console.log('object')
        return Promise.reject(new Error(res.data))
      }
    },
    // 获取用户信息
    async getUserInfo() {
      let res: userInfoResponseData = await reqUserInfo()
      if (res.code === 200) {
        this.name = res.data.name
        this.avatar = res.data.avatar
        // 计算当前用户需要展示的异步路由
        let userAsyncRoutes = filterAsyncRoutes(cloneDeep(asyncRoutes), res.data.routes)
        this.buttons = res.data.buttons;
        this.menuRoutes = [...constantRoutes, ...userAsyncRoutes, anyRoutes];
        [...userAsyncRoutes, anyRoutes].forEach((route: any) => {
          router.addRoute(route);
      });
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    // 退出登录
    async userLogout() {
      let res = await reqLogout()
      if (res.code === 200) {
        this.token = ''
        this.name = ''
        this.avatar = ''
        localStorage.removeItem('TOKEN')
        return 'ok'
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
  },
})

export default useUserStore
